package com.oktago.ibore;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {

    private ProgressDialog progressDialog;
    private final static int WAITING_PROGRESS_DIALOG_ID = 1;
    private Handler myHandler;
    private int status; // 0)Download Token 1)Download Server Response
    String token;
    String username;
    String password;
    String root;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        Button button = (Button) findViewById(R.id.ButtonLogin);

        myHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.obj.toString().equals("")) {
                    Toast t = Toast.makeText(LoginActivity.this, "Error in connection...", Toast.LENGTH_SHORT);
                    t.show();
                    dismissDialog(WAITING_PROGRESS_DIALOG_ID);
                    return;
                }
                if (status == 0) {
                    token = msg.obj.toString();
                    token = token.substring(1); //rimuoviamo la prima "
                    token = token.substring(0, token.length() - 1);
                    status = 1;
                    startDownloadPOST();
                    return;
                }

                if (status == 1) {
                    if (msg.obj.toString().equals("1")) {//Connessione ok
                        setLogged(true);
                        status = 2;
                    }
                    dismissDialog(WAITING_PROGRESS_DIALOG_ID);
                }
            }
        };


        button.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                EditText et = (EditText) findViewById(R.id.userame);
                Log.i("Login", "User->" + et.getText().toString());
                username = et.getText().toString();
                EditText et2 = (EditText) findViewById(R.id.password);
                Log.i("Login", "Passw->" + et2.getText().toString());
                password = et2.getText().toString();
                if (username.equals("") || password.equals("")) {
                    Toast t = Toast.makeText(LoginActivity.this, "User and Login are required", Toast.LENGTH_SHORT);
                    t.show();
                } else {
                    login(et.getText().toString(), et2.getText().toString());
                }
            }
        });
    }

    private void login(String user, String pw) {
        status = 0;
        startDownloadGET(/*url + "/index.php?option=com_bore&index.php?option=com_bore&controller=auth&task=getToken"*/);
        showDialog(WAITING_PROGRESS_DIALOG_ID);
    }//login

    private void startDownloadGET(/*final String urlToDownload*/) {
        Thread downloader = new Thread() {

            @Override
            public void run() {
                try {
                    IBoreApplication application = (IBoreApplication) getApplication();
                    application.startDownloadGet(myResponseHandler);
                } catch (Exception e) {
                    showMessageOnOutput("");
                }
            }
        };

        // Visualizziamo una Dialog di attesa
        showDialog(WAITING_PROGRESS_DIALOG_ID);
        // Lo avviamo
        downloader.start();


    }//startDownloadGET

    private void startDownloadPOST() {
        Thread downloader = new Thread() {

            @Override
            public void run() {
                try {
                    IBoreApplication application = (IBoreApplication) getApplication();
                    application.startDownloadPost(myResponseHandler, username, password, token);
                } catch (Exception e) {
                    Log.e("Pubblication Activity", "" + e);
                    showMessageOnOutput("");
                }
            }
        };

        // Visualizziamo una Dialog di attesa
        showDialog(WAITING_PROGRESS_DIALOG_ID);
        // Lo avviamo
        downloader.start();
    }

    public void showMessageOnOutput(String result) {
        Message msg = myHandler.obtainMessage();
        msg.obj = result;
        myHandler.sendMessage(msg);
    }
    private final ResponseHandler<String> myResponseHandler = new ResponseHandler<String>() {

        public String handleResponse(HttpResponse response)
                throws ClientProtocolException, IOException {
            // Estraiamo il risultato dalla risposta. Otteniamo quindi il content
            // da cui leggere le informazioni
            InputStream content = response.getEntity().getContent();
            byte[] buffer = new byte[1024];
            int numRead = 0;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while ((numRead = content.read(buffer)) != -1) {
                baos.write(buffer, 0, numRead);
            }
            // Chiudiamo lo stream
            content.close();
            // Otteniamo il risultato
            String result = new String(baos.toByteArray());
            showMessageOnOutput(result);

            return result;
        }
    };

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case WAITING_PROGRESS_DIALOG_ID:
                progressDialog = new ProgressDialog(this,
                        ProgressDialog.STYLE_SPINNER);
                progressDialog.setTitle("HTTP Connection");
                progressDialog.setMessage("Connecting...");
                progressDialog.setIndeterminate(true);
                return progressDialog;
            default:
                return null;
        }
    }

    public void setLogged(boolean loginOK) {
        if (loginOK) {
            IBoreApplication iBoreApplication = (IBoreApplication) getApplication();
            iBoreApplication.setLogged(username, password, token);
            ((IBoreApplication)getApplication()).loginActivated=true;
            finish();
        } else {
            Toast t = Toast.makeText(LoginActivity.this, "Login incorrect, please try again.", Toast.LENGTH_SHORT);
            t.show();
        }
    }
}
